from json import (dumps, loads)
from flask import (Blueprint, request, make_response)
from service.call_service import (save_call, get_call, fix_call_class, fix_call_major, fix_call_department)
from service.user_service import get_student_by_class_id

call_ = Blueprint('call', __name__, url_prefix='/call')


@call_.route('/submit_call', methods=('get', 'post'))
def submit_call():
    # print(request.json)
    b, msg = save_call(request.json)
    return dumps({
        'code': 200 if b else 500,
        'msg': msg
    })


@call_.route('/getRecordByztj_course_id_class_id', methods=('get', 'post'))
def get_record():
    print(request.json)
    z_t_j = request.json["z_t_j"]
    z = z_t_j[0].split('_')[1]
    t = z_t_j[1].split('_')[1]
    j = z_t_j[2].split('_')[1]
    course_id = request.json["course_id"]
    class_id = request.json["class_id"]
    students = get_student_by_class_id(class_id)
    res = get_call(z, t, j, course_id, class_id)
    code = 200
    msg = ''
    if not res or len(res) == 0:
        code = 500
        msg = '查无本节次考勤数据！'
    else:
        for index, student in enumerate(students):
            student["id"] = index + 1
            student["s"] = next(filter(lambda x: x["user_id"] == student["u_id"], res).__iter__())["state"]
    # for student in students:
    #     print(student)
    return dumps(
        {
            'code': code,
            'msg': msg,
            'data': students
        }
    )


@call_.route("/fix_call", methods=("get", "post"))
def fix_call():
    # print(request.json)
    # 0.求出两次出勤比较
    now_at_number = 0
    records = request.json
    for record in records:
        if record["state"] == 0:
            now_at_number += 1
    n = now_at_number - records[0]["before_at_number"]
    print(n)
    # 0.1.求出week, day, th, c_id, m_id
    week = records[0]["week"]
    day = records[0]["day"]
    th = records[0]["th"]
    c_id = records[0]["u_c_id"]
    m_id = records[0]["m_id"]

    # # 如果出勤人次无变化则无需修改专业和院系
    b = True
    if n == 0:
        b = False

    # # 1.更新班级表
    fix_call_class(records, week, day, th, c_id)
    # # 2.更新专业表
    if b:
        fix_call_major(week, day, m_id, n)
    # # 3.更新院系表
    if b:
        fix_call_department(week, day, m_id, n)
    return dumps({
        'code': 200,
        'msg': '更新成功！'
    })